import Vue from "vue"
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	// 数据参数
	state:{
		allList:[],
		isLogin:localStorage.getItem('uid')||sessionStorage.getItem('uid')||''
	},
	// 计算属性
	getters:{
		num(state){
			return state.allList.length
		},
		checkedNum(state){
			let num=0;
			state.allList.forEach((item)=>{
				if(item.checked){
					num+=1
				}
			})
			return num
		},
		price(state){
			let price=0
			state.allList.forEach((item)=>{
				if(item.checked){
					price+=item.promotionPrice*item.num
				}
			})
			return price
		}
	},
	// 同步方法
	mutations:{
		ulogin(state,uid){
			state.isLogin=uid
		},
		logout(state){
			state.isLogin=null
		},
		add(state,obj){
			console.log(obj);
			let idx=null
			// console.log('add触发');
			state.allList.forEach((item,index)=>{
				if(item.id==obj.id){
					idx=index
				}
			})
			idx!==null?state.allList[idx].num+=1:state.allList.push(obj)
			localStorage.setItem('cart',JSON.stringify(state.allList))
		},
		minus(state,id){
			let idx=null
			// console.log('minus触发');
			state.allList.forEach((item,index)=>{
				if(item.id==id){
					if(state.allList[index].num==1)return;
					state.allList[index].num-=1
				}
			})
			localStorage.setItem('cart',JSON.stringify(state.allList))
		},
		del(state){
			let {allList}=state
			let arr=[]
			allList.forEach((item,index)=>{
				if(item.checked){
					arr.push(index)
				}
			})
			for(let i=allList.length-1;i>=0;i--){
				arr.forEach((item)=>{
					if(item==i){
						allList.splice(i,1)
					}
				})
			}
			localStorage.setItem('cart',JSON.stringify(allList))
		},
		changeCheckState(state,index){
			state.allList[index].checked=!state.allList[index].checked
			localStorage.setItem('cart',JSON.stringify(state.allList))
		},
		changeAllState(state,val){
			state.allList.forEach((item=>{
				item.checked=!val
			}))
			localStorage.setItem('cart',JSON.stringify(state.allList))
		}
		
	},
	// 异步方法
	actions:{
		
	}
})

export default store
